const { getCurrentTime, isEmpty } = require("./utils")

/**
 * 创建订单号
 */
const createOrderId = async () => {
  return new Promise((resolve, reject) => {
    try {
      let _date = new Date()
      let _ts = _date.getTime()
      let _year = _date.getFullYear()
      let _month = _date.getMonth() + 1
      let _day = _date.getDate()
      let _h = _date.getHours()
      let _m = _date.getMinutes()

      const date = `${_year}${zero(_month)}${zero(_day)}${zero(_h)}${zero(_m)}`
      const randomNum = parseInt(Math.random() * (0 - 100), 10)

      const orderId = `${date}${_ts}`
      resolve(orderId)
    } catch (error) {
      reject("订单号创建失败：" + error)
    }
  })
}

//数值补0方法
const zero = (value) => {
  if (value < 10) return "0" + value
  return value
}

/**
 * 计算台桌费用
 * @param {Object} opts
 * @param {String} opts.start_time 开始时间(13位时间戳)
 * @param {Int} opts.price  非会员价格
 * @param {Int} opts.vip_price  会员价格
 * @param {Int} opts.phone  会员手机号
 * @returns
 */
const handleCalculateCost = async (opts) => {
  const { start_time, price, vip_price, way, phone } = opts

  // const rules_price = isEmpty(phone) ? price : vip_price  //有手机号，则是会员
  const _duration = getCurrentTime("ts") - start_time
  const minuteCount = Math.floor(_duration / 1000 / 60) //总的分钟数
  const hour = Math.floor(minuteCount / 60) //小时
  const minute = minuteCount % 60 //分钟
  let duration = 0
  let cost = 0
  let vip_cost = 0  //vip价格

  // console.log('opts', opts)
  // console.log('rules_price', rules_price)

  // 计算时长
  if (minuteCount > 60) {
    duration = `${hour}时${minute}分  - ${minuteCount}`
  } else {
    duration = `${minuteCount}分钟`
  }

  // 时长大于零
  if (minuteCount > 0) {
    // 计费方式1
    if (!way) {
      cost = Math.floor((minuteCount * price) / 60) //向下取整
      if (!isEmpty(phone)) {
        vip_cost = Math.floor((minuteCount * vip_price) / 60) //向下取整
      }
    }
  }

  return {
    cost,
    vip_cost,
    duration,
    hour,
    minute,
  }
}

/**
 * 计算时间差
 * @param {Object} opts
 * @param {String} opts.start_time 开始时间戳
 * @param {String} opts.end_time 结束时间戳
 * @returns
 */
const calculateDifference = async (opts) => {
  const { start_time, end_time } = opts

  const _duration = end_time - start_time
  const minuteCount = Math.floor(_duration / 1000 / 60) //总的分钟数（向上取整）
  const hour = Math.floor(minuteCount / 60) //小时（向下取整）
  const minute = minuteCount % 60 //分钟
  let duration = 0

  // 分钟数大于零
  if (minuteCount > 0) {
    if (minuteCount >= 60) {
      duration = minuteCount === 60 ? `${hour}小时` : `${hour}小时${minute}分钟`
    } else {
      duration = `${minuteCount}分钟`
    }
  }

  return duration
}

module.exports = {
  createOrderId,
  handleCalculateCost,
  calculateDifference
}
